package com.hands.sample.service.impl;

import com.hands.commen.entity.wx.MsgEntity;
import com.hands.commen.utils.GZipHelper;
import com.hands.commen.utils.Utils;
import com.hands.service.WxxRpcService;
import com.hands.sample.service.InstructionsInfoService;
import net.sf.json.JSONObject;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.rpc.RpcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@Service
public class InstructionsInfoServiceImpl implements InstructionsInfoService {

    private static final Logger logger = LoggerFactory.getLogger(InstructionsInfoServiceImpl.class);

    @Reference(interfaceClass = WxxRpcService.class, version = "1.0.1", async = true,check = false,timeout = 2500)
    private WxxRpcService  wxxRpcService;

    @Override
    public String requestHaierSocket(MsgEntity args) throws ExecutionException, InterruptedException {
        logger.info("请求数据：{}",args);
        String ret = null;
        String reponseMsg="";
        //通过dubbo发送数据
        reponseMsg = wxxRpcService.InstructionsInfo(args);
        Future<String> future = RpcContext.getContext().getFuture();
        logger.info("future的值为{},直接获取的数据{}",future,reponseMsg);
        String futureInfo = future.get();

        if(future !=null){
            while (true){
                if(futureInfo !=null ){
                    reponseMsg =futureInfo;
                    break;

                }else{

                    futureInfo = future.get();
                }

            }
        }
        logger.info("reponseMsg={}",reponseMsg);
        logger.info("-----------------------end------------------------");
        if(reponseMsg==null){
            return  "{\"statusCode\": "+9999+",\"message\": \""+"主机不在线"+"\",\"result\":"+ret+"}";
        }
        JSONObject jsonObject = JSONObject.fromObject(reponseMsg);
        Object body = jsonObject.get("body");
        if(body !=null){
            reponseMsg = jsonObject.get("body").toString();
            byte[] bytes = Utils.decodeByteBase64(reponseMsg);
            ret = GZipHelper.uncompress(bytes);
        }
        String code=jsonObject.getJSONObject("header").getString("respCode");
        String message=jsonObject.getJSONObject("header").getString("respMsg");
        ret = "{\"statusCode\": "+code+",\"message\": \""+message+"\",\"result\":"+ret+"}";
        return ret;
    }
}
